<template>
  <div class="vue-box" style="display: none;" :style="'display: block;'">
    <el-dialog v-bind="$attrs"
               :visible.sync="dialogVisible"
               :append-to-body="true"
               :close-on-click-modal="false"
               v-on="$listeners" @open="onOpen" @close="onClose" :title="dialogTitle">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="small" label-width="100px">
          <el-col :span="24">
            <el-form-item label="父级菜单" prop="pid">
              <el-cascader v-model="formData.pid" :options="pidOptions" :props="pidProps"
                           :disabled="disFlag"
                           :style="{width: '100%'}" placeholder="请选择选择联级父级菜单" clearable
                           filterable></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单类型" prop="type">
              <el-radio-group v-model="formData.type"
                              :disabled="disFlag"
                              size="small">
                <el-radio v-for="(item, index) in typeOptions" :key="index" :label="item.value"
                          :disabled="item.disabled">{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入菜单名称" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单图标" prop="icon">
              <el-autocomplete
                  :style="{width: '100%'}"
                  popper-class="my-autocomplete"
                  v-model="formData.icon"
                  :fetch-suggestions="querySearch"
                  placeholder="请选择菜单图标"
                  @select="handleSelect">
                <i
                    class="el-input__icon" :class="formData.icon"
                    slot="suffix">
                </i>
                <el-button slot="append" icon="el-icon-thumb" @click="dialogSelect=true">选择</el-button>
                <template slot-scope="{ item }">
                  <i :class="item"></i>
                  <span>{{ item }}</span>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单URL" prop="url">
              <el-input v-model="formData.url" placeholder="请输入菜单URL" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单权限" prop="permission">
              <el-input v-model="formData.permission" placeholder="请输入菜单权限" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="sort">
              <el-input-number v-model="formData.sort" placeholder="显示顺序" :step='1'></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否显示" prop="isBlank" required>
              <el-switch v-model="formData.isShow" active-text="显示" inactive-text="隐藏"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="外部连接" prop="isBlank" required>
              <el-switch v-model="formData.isBlank" active-text="是" inactive-text="否"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="info">
              <el-input v-model="formData.info" type="textarea" placeholder="请输入备注"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
        :visible.sync="dialogSelect"
        :append-to-body="true"
        width="80%"
        top="5vh"
        v-on="$listeners">
      <template slot="title">
        选择图标
        <div class="c-item">
          <el-input
              placeholder="输入图标名进行过滤"
              v-model="iconName"
              clearable>
          </el-input>
        </div>
      </template>

      <div style="display: grid;
      height: 65vh; overflow: auto;
      grid-template-columns: repeat(6,15%);
      justify-content: center;">
        <div class="icon-menu" @click="handleSelect(item)"
             style="display: flex;
                    height: 80px;
                    align-items: center;
                    cursor: pointer;
                    padding: 5px;
                    flex-direction: column;
                    justify-content: center;" v-for="item in iconList" :key="item">
          <i :class="item" style="font-size: 30px"></i>
          <div>{{ item }}</div>
        </div>
      </div>

    </el-dialog>
    <div class="c-panel">
      <!-- ------------- 检索参数 ------------- -->
      <div class="c-title">菜单管理</div>
      <!-- <div class="c-title">数据列表</div> -->
      <!-- ------------- 快捷按钮 ------------- -->
      <div class="fast-btn">
        <el-button type="primary" icon="el-icon-plus"
                   @click="dialogVisible = true;disFlag=false;dialogTitle='新增菜单'">
          新增
        </el-button>
        <div class="c-item">
          <el-input
              placeholder="输入关键字进行过滤"
              v-model="filterText"
              clearable>
          </el-input>
        </div>
        <el-button-group>
          <el-button type="success" v-show="!expandAll" @click="setAllExpand">展开</el-button>
          <el-button type="info" v-show="expandAll" @click="setAllFold">收起</el-button>
          <el-button type="primary" v-if="sa.$sys.isAuth('menu:import-menu')" @click="importMenu">导入<i
              class="el-icon-upload2 el-icon--right"></i></el-button>
          <el-button type="primary" v-if="sa.$sys.isAuth('menu:export')" @click="exportMenu">导出<i
              class="el-icon-download el-icon--right"></i></el-button>
        </el-button-group>

      </div>
      <div>名称 | url | 权限 | 类别 | 排序 | 备注</div>
      <el-tree
          ref="tree"
          :data="dataList"
          node-key="id"
          :default-expand-all="expandAll"
          :filter-node-method="filterNode"
          @node-expand="nodeExpand"
          @node-collapse="nodeCollapse"
          :default-expanded-keys="expandArr"
      >
					<span class="custom-tree-node" slot-scope="s">
            <div>
              <span><i :class="s.data.icon"></i></span>
              <span title="菜单名称" style="color: #2D8CF0;" v-if="s.data.isShow === undefined || s.data.isShow">{{
                  s.data.name
                }}</span>
              <span style="color: #999;" v-if="s.data.isShow === false">{{ s.data.name }} (隐藏)</span>
              <span> | </span>
              <span title="菜单url" style="color: #2D8CF0;">{{ s.data.url }}</span>
              <span> | </span>
              <span title="菜单权限" style="color: #2D8CF0;">{{ s.data.permission }}</span>
              <span> | </span>
              <span title="菜单类型" style="color: #2D8CF0;">
                <el-tag v-if="s.data.type === 1">菜单</el-tag>
                        <el-tag type="warning" v-if="s.data.type === 2">按钮</el-tag>
              </span>
              <span> | </span>
              <span title="排序" style="color: #2D8CF0;">{{ s.data.weight }}</span>
              <span> | </span>
              <span title="备注" style="color: #999; width: 50%" v-if="s.data.info">{{
                  s.data.info.slice(0, 26)
                }} {{ s.data.info.length > 26 ? '...' : '' }} </span>
              <span> | </span>
              <span style="float: right">
                <el-link type="success" v-if="s.data.type === 1 && s.data.menuLevel < 3"
                         @click.stop="addMenu(s.data.id)">新增菜单</el-link>
                <el-link type="warning" v-if="s.data.type === 1" @click.stop="addButton(s.data.id)">新增按钮</el-link>

                <el-popover
                    placement="left"
                    width="650"
                    @show="show(s.data.id)"
                    :open-delay="200"
                    :close-delay="200"
                    trigger="hover">
                  <el-descriptions title="菜单信息" size="medium">
                      <el-descriptions-item label="名称"><i
                          :class="showData.icon"></i>{{ showData.name }}</el-descriptions-item>
                      <el-descriptions-item label="菜单地址">{{ showData.url }}</el-descriptions-item>
                      <el-descriptions-item label="权限编码">{{ showData.permission }}</el-descriptions-item>
                      <el-descriptions-item label="类型">
                        <el-tag v-if="showData.type === 1">菜单</el-tag>
                        <el-tag type="warning" v-if="showData.type === 2">按钮</el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item label="显示顺序">{{ showData.sort }}</el-descriptions-item>
                    <el-descriptions-item label="是否外链">
                        <el-tag v-if="showData.isBlank">是外链</el-tag>
                        <el-tag v-else>非外链</el-tag>
                      </el-descriptions-item>
                    <el-descriptions-item label="状态">
                        <el-tag v-if="showData.isShow">显示</el-tag>
                        <el-tag v-else>隐藏</el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item label="备注">{{ showData.info }}</el-descriptions-item>
                  </el-descriptions>
                 <el-link type="info" slot="reference" @click.stop="">详情</el-link>
                </el-popover>

                <el-link type="primary" @click.stop="edit(s.data.id)">修改</el-link>
                <el-popconfirm
                    trigger="hover"
                    @confirm="del(s.data.id)"
                    title="确认删除，删除父级会删除其下所有子项，确认删除！！"
                >
                <el-link type="danger" slot="reference" @click.stop="">删除</el-link>
              </el-popconfirm>
              </span>
            </div>
					</span>
      </el-tree>
    </div>
  </div>
</template>

<script>
let PATH = "/menu"
let expandTag = "menu"
module.exports = {
  watch: {
    filterText: _.debounce(function (val) {
      this.$refs.tree.filter(val)
    }, 500),
    iconName(val) {
      const iconTemp = this.loadAll();
      this.iconList = val ? iconTemp.filter(this.createFilter(val)) : iconTemp;
    },
    'formData.url': function (val) {
      if (val) {
        let trim = val.trim();
        if (trim[0] === '/') {
          trim = trim.slice(1);
        }
        trim = trim.replaceAll('/', ':').replaceAll('.vue', '').replaceAll('.html', '')
        this.formData.permission = trim;
      }
    }
  },
  data() {
    return {
      expandAll: sa.getItem(expandTag),
      iconName: '',
      expandArr: [],
      dialogSelect: false,
      filterText: '',
      dialogTitle: '',
      disFlag: false,
      dataList: [],
      restaurants: [],
      dialogVisible: false,
      formData: {
        id: '',
        pid: '0',
        type: 1,
        name: undefined,
        icon: undefined,
        url: undefined,
        permission: undefined,
        sort: 0,
        isShow: true,
        isBlank: false,
        info: undefined,
      },
      showData: {
        id: '',
        pid: '0',
        type: 1,
        name: undefined,
        icon: undefined,
        url: undefined,
        permission: undefined,
        sort: 0,
        isShow: true,
        isBlank: false,
        info: undefined,
      },
      rules: {
        pid: [{
          required: true,
          message: '请至少选择一个父级菜单',
          trigger: 'change'
        }],
        type: [{
          required: true,
          message: '菜单类型不能为空',
          trigger: 'change'
        }],
        name: [{
          required: true,
          message: '请输入菜单名称',
          trigger: 'blur'
        }],
        url: [{
          required: true,
          message: '请输入菜单URL',
          trigger: 'blur'
        }],
        permission: [{
          required: true,
          message: '请输入菜单权限',
          trigger: 'blur'
        }],
        sort: [{
          required: true,
          message: '显示顺序',
          trigger: 'blur'
        }],
        info: [],
      },
      pidOptions: [],
      typeOptions: [{
        "label": "菜单",
        "value": 1
      }, {
        "label": "按钮",
        "value": 2
      }],
      pidProps: {
        "multiple": false,
        "expandTrigger": 'hover',
        "label": "label",
        "value": "value",
        "children": "children",
        "checkStrictly": true,
        "emitPath": false
      },
      iconList: []
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1
          || data.permission.indexOf(value) !== -1
          || data.url.indexOf(value) !== -1
          ;
    },
    show(id) {
      sa.ajax(PATH + '/get', {id: id}, (res) => {
        this.showData = res.data;
      }, {type: 'get', msg: null})
    },
    edit(id) {
      sa.ajax(PATH + '/get', {id: id}, (res) => {
        this.formData = res.data;
        this.dialogTitle = '编辑菜单'
        this.dialogVisible = true;
        this.disFlag = false
      }, {type: 'get', msg: null})
    },
    del(id) {
      sa.ajax(PATH + '/del', {id: id}, (res) => {
        sa.alert(res.msg, () => {
          this.f5();
        })
      }, {type: 'get', msg: null})
    },
    addMenu(pid) {
      this.dialogTitle = '新增菜单'
      this.disFlag = true
      this.formData.pid = pid
      this.formData.type = 1
      this.dialogVisible = true;
    },
    addButton(pid) {
      this.dialogTitle = '新增按钮'
      this.disFlag = true
      this.formData.pid = pid
      this.formData.type = 2
      this.dialogVisible = true;
    },
    // 折叠所有节点
    setAllFold() {
      this.expandArr = []
      sa.setItem(expandTag, false)
      this.expandAll = false
      for (let i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
        this.$refs.tree.store._getAllNodes()[i].expanded = false;
      }
    },
    // 展开所有节点
    setAllExpand() {
      this.expandArr = []
      sa.setItem(expandTag, true)
      this.expandAll = true
      for (let i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
        this.$refs.tree.store._getAllNodes()[i].expanded = true;
      }
    },
    f5() {
      sa.ajax(PATH + "/list", {}, (res) => {
        this.dataList = res.data;
      }, {type: 'get'})
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.indexOf(queryString) >= 0);
      };
    },
    loadAll() {
      // 人肉爬虫
      return ["el-icon-platform-eleme", "el-icon-eleme", "el-icon-delete-solid", "el-icon-delete", "el-icon-s-tools", "el-icon-setting", "el-icon-user-solid", "el-icon-user", "el-icon-phone", "el-icon-phone-outline", "el-icon-more", "el-icon-more-outline", "el-icon-star-on", "el-icon-star-off", "el-icon-s-goods", "el-icon-goods", "el-icon-warning", "el-icon-warning-outline", "el-icon-question", "el-icon-info", "el-icon-remove", "el-icon-circle-plus", "el-icon-success", "el-icon-error", "el-icon-zoom-in", "el-icon-zoom-out", "el-icon-remove-outline", "el-icon-circle-plus-outline", "el-icon-circle-check", "el-icon-circle-close", "el-icon-s-help", "el-icon-help", "el-icon-minus", "el-icon-plus", "el-icon-check", "el-icon-close", "el-icon-picture", "el-icon-picture-outline", "el-icon-picture-outline-round", "el-icon-upload", "el-icon-upload2", "el-icon-download", "el-icon-camera-solid", "el-icon-camera", "el-icon-video-camera-solid", "el-icon-video-camera", "el-icon-message-solid", "el-icon-bell", "el-icon-s-cooperation", "el-icon-s-order", "el-icon-s-platform", "el-icon-s-fold", "el-icon-s-unfold", "el-icon-s-operation", "el-icon-s-promotion", "el-icon-s-home", "el-icon-s-release", "el-icon-s-ticket", "el-icon-s-management", "el-icon-s-open", "el-icon-s-shop", "el-icon-s-marketing", "el-icon-s-flag", "el-icon-s-comment", "el-icon-s-finance", "el-icon-s-claim", "el-icon-s-custom", "el-icon-s-opportunity", "el-icon-s-data", "el-icon-s-check", "el-icon-s-grid", "el-icon-menu", "el-icon-share", "el-icon-d-caret", "el-icon-caret-left", "el-icon-caret-right", "el-icon-caret-bottom", "el-icon-caret-top", "el-icon-bottom-left", "el-icon-bottom-right", "el-icon-back", "el-icon-right", "el-icon-bottom", "el-icon-top", "el-icon-top-left", "el-icon-top-right", "el-icon-arrow-left", "el-icon-arrow-right", "el-icon-arrow-down", "el-icon-arrow-up", "el-icon-d-arrow-left", "el-icon-d-arrow-right", "el-icon-video-pause", "el-icon-video-play", "el-icon-refresh", "el-icon-refresh-right", "el-icon-refresh-left", "el-icon-finished", "el-icon-sort", "el-icon-sort-up", "el-icon-sort-down", "el-icon-rank", "el-icon-loading", "el-icon-view", "el-icon-c-scale-to-original", "el-icon-date", "el-icon-edit", "el-icon-edit-outline", "el-icon-folder", "el-icon-folder-opened", "el-icon-folder-add", "el-icon-folder-remove", "el-icon-folder-delete", "el-icon-folder-checked", "el-icon-tickets", "el-icon-document-remove", "el-icon-document-delete", "el-icon-document-copy", "el-icon-document-checked", "el-icon-document", "el-icon-document-add", "el-icon-printer", "el-icon-paperclip", "el-icon-takeaway-box", "el-icon-search", "el-icon-monitor", "el-icon-attract", "el-icon-mobile", "el-icon-scissors", "el-icon-umbrella", "el-icon-headset", "el-icon-brush", "el-icon-mouse", "el-icon-coordinate", "el-icon-magic-stick", "el-icon-reading", "el-icon-data-line", "el-icon-data-board", "el-icon-pie-chart", "el-icon-data-analysis", "el-icon-collection-tag", "el-icon-film", "el-icon-suitcase", "el-icon-suitcase-1", "el-icon-receiving", "el-icon-collection", "el-icon-files", "el-icon-notebook-1", "el-icon-notebook-2", "el-icon-toilet-paper", "el-icon-office-building", "el-icon-school", "el-icon-table-lamp", "el-icon-house", "el-icon-no-smoking", "el-icon-smoking", "el-icon-shopping-cart-full", "el-icon-shopping-cart-1", "el-icon-shopping-cart-2", "el-icon-shopping-bag-1", "el-icon-shopping-bag-2", "el-icon-sold-out", "el-icon-sell", "el-icon-present", "el-icon-box", "el-icon-bank-card", "el-icon-money", "el-icon-coin", "el-icon-wallet", "el-icon-discount", "el-icon-price-tag", "el-icon-news", "el-icon-guide", "el-icon-male", "el-icon-female", "el-icon-thumb", "el-icon-cpu", "el-icon-link", "el-icon-connection", "el-icon-open", "el-icon-turn-off", "el-icon-set-up", "el-icon-chat-round", "el-icon-chat-line-round", "el-icon-chat-square", "el-icon-chat-dot-round", "el-icon-chat-dot-square", "el-icon-chat-line-square", "el-icon-message", "el-icon-postcard", "el-icon-position", "el-icon-turn-off-microphone", "el-icon-microphone", "el-icon-close-notification", "el-icon-bangzhu", "el-icon-time", "el-icon-odometer", "el-icon-crop", "el-icon-aim", "el-icon-switch-button", "el-icon-full-screen", "el-icon-copy-document", "el-icon-mic", "el-icon-stopwatch", "el-icon-medal-1", "el-icon-medal", "el-icon-trophy", "el-icon-trophy-1", "el-icon-first-aid-kit", "el-icon-discover", "el-icon-place", "el-icon-location", "el-icon-location-outline", "el-icon-location-information", "el-icon-add-location", "el-icon-delete-location", "el-icon-map-location", "el-icon-alarm-clock", "el-icon-timer", "el-icon-watch-1", "el-icon-watch", "el-icon-lock", "el-icon-unlock", "el-icon-key", "el-icon-service", "el-icon-mobile-phone", "el-icon-bicycle", "el-icon-truck", "el-icon-ship", "el-icon-basketball", "el-icon-football", "el-icon-soccer", "el-icon-baseball", "el-icon-wind-power", "el-icon-light-rain", "el-icon-lightning", "el-icon-heavy-rain", "el-icon-sunrise", "el-icon-sunrise-1", "el-icon-sunset", "el-icon-sunny", "el-icon-cloudy", "el-icon-partly-cloudy", "el-icon-cloudy-and-sunny", "el-icon-moon", "el-icon-moon-night", "el-icon-dish", "el-icon-dish-1", "el-icon-food", "el-icon-chicken", "el-icon-fork-spoon", "el-icon-knife-fork", "el-icon-burger", "el-icon-tableware", "el-icon-sugar", "el-icon-dessert", "el-icon-ice-cream", "el-icon-hot-water", "el-icon-water-cup", "el-icon-coffee-cup", "el-icon-cold-drink", "el-icon-goblet", "el-icon-goblet-full", "el-icon-goblet-square", "el-icon-goblet-square-full", "el-icon-refrigerator", "el-icon-grape", "el-icon-watermelon", "el-icon-cherry", "el-icon-apple", "el-icon-pear", "el-icon-orange", "el-icon-coffee", "el-icon-ice-tea", "el-icon-ice-drink", "el-icon-milk-tea", "el-icon-potato-strips", "el-icon-lollipop", "el-icon-ice-cream-square", "el-icon-ice-cream-round"];
    },
    handleSelect(item) {
      this.formData.icon = item;
      this.dialogSelect = false;
    },
    onOpen() {

    },
    onClose() {
      this.formData = {
        id: '',
        pid: '0',
        type: 1,
        sort: 0,
        isShow: true,
        isBlank: false
      }
      this.$refs['elForm'].resetFields()
    },
    close() {
      this.dialogVisible = false;
    },
    handelConfirm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        sa.ajax(PATH + "/save-or-update", this.formData, (res) => {
          sa.alert(res.msg, () => {
            this.f5()
            this.close()
          })
        }, {})
      })
    },
    getPidOptions() {
      sa.ajax(PATH + "/parentList", {}, (res) => {
        this.pidOptions = res.data
      }, {type: 'get', msg: null})
    },
    exportMenu() {
      sa.downLoadFile(sa.cfg.api_url + PATH + "/export", {}, "GET")
    },
    importMenu() {
      sa.uploadFn(sa.cfg.api_url + PATH + '/import-menu', (res) => {
        sa.alert(res, () => {
          sa.f5()
        })
      })
    },
    nodeExpand(data) {
      let arr = this.expandArr
      arr.push(data.id)
      this.expandArr = arr
    },
    nodeCollapse(data) {
      let arr = this.expandArr
      arr.splice(arr.indexOf(data.id), 1)
      this.expandArr = arr
    },
  },
  mounted() {
    this.restaurants = this.loadAll();
    this.iconList = this.loadAll();
    this.getPidOptions();

  },
  created() {
    this.f5()
  }
}
</script>

<style>
.el-tree .custom-tree-node {
  width: 100%;
}

.icon-menu:hover {
  background-color: rgba(217, 214, 214, 0.99)
}
</style>
